import React, { useState, useEffect } from 'react';
import { Layout, Menu, Input, Badge, Avatar, Dropdown, Button, message } from 'antd';
import { 
  HomeOutlined, 
  BookOutlined, 
  ShoppingCartOutlined, 
  UserOutlined,
  LogoutOutlined,
  LoginOutlined,
  ProfileOutlined,
  ShoppingOutlined
} from '@ant-design/icons';
import { Link, useNavigate, Outlet, useLocation } from 'react-router-dom';
import { authApi } from '../../api';

const { Header, Content, Footer } = Layout;
const { Search } = Input;

const FrontLayout = () => {
  const [selectedKeys, setSelectedKeys] = useState(['home']);
  const navigate = useNavigate();
  const location = useLocation();
  const isAuthenticated = authApi.isAuthenticated();
  const currentUser = authApi.getCurrentUser();

  useEffect(() => {
    // 根据当前路径设置选中的菜单项
    const pathSegments = location.pathname.split('/');
    const currentPath = pathSegments[1] || 'home';
    setSelectedKeys([currentPath]);
  }, [location.pathname]);

  // 处理搜索
  const handleSearch = (value) => {
    navigate(`/books?search=${encodeURIComponent(value)}`);
  };

  // 处理登出
  const handleLogout = () => {
    authApi.logout();
    message.success('已退出登录');
    navigate('/');
  };

  // 用户菜单
  const userMenu = (
    <Menu>
      <Menu.Item key="profile" icon={<ProfileOutlined />}>
        <Link to="/profile">个人中心</Link>
      </Menu.Item>
      <Menu.Item key="orders" icon={<ShoppingOutlined />}>
        <Link to="/orders">我的订单</Link>
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout" icon={<LogoutOutlined />} onClick={handleLogout}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <Layout className="layout">
      <Header style={{ 
        position: 'fixed', 
        zIndex: 1, 
        width: '100%', 
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '0 50px'
      }}>
        <div className="logo" style={{ 
          color: 'white', 
          fontSize: '24px', 
          fontWeight: 'bold',
          marginRight: '40px'
        }}>
          图书商城
        </div>
        <div style={{ display: 'flex', flex: 1 }}>
          <Menu
            theme="dark"
            mode="horizontal"
            selectedKeys={selectedKeys}
            items={[
              {
                key: 'home',
                icon: <HomeOutlined />,
                label: <Link to="/">首页</Link>
              },
              {
                key: 'books',
                icon: <BookOutlined />,
                label: <Link to="/books">全部书籍</Link>
              }
            ]}
          />
          <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
            <Search
              placeholder="搜索书籍"
              allowClear
              enterButton
              onSearch={handleSearch}
              style={{ width: 300 }}
            />
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Badge count={0} showZero={false}>
            <Button 
              type="text" 
              icon={<ShoppingCartOutlined style={{ fontSize: '20px', color: 'white' }} />} 
              onClick={() => navigate('/cart')}
              style={{ marginRight: '20px' }}
            />
          </Badge>
          
          {isAuthenticated ? (
            <Dropdown overlay={userMenu} placement="bottomRight">
              <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
                <Avatar icon={<UserOutlined />} />
                <span style={{ color: 'white', marginLeft: '8px' }}>{currentUser?.username}</span>
              </div>
            </Dropdown>
          ) : (
            <div>
              <Button 
                type="text" 
                icon={<LoginOutlined />} 
                onClick={() => navigate('/login')}
                style={{ color: 'white' }}
              >
                登录
              </Button>
              <Button 
                type="primary" 
                onClick={() => navigate('/register')}
              >
                注册
              </Button>
            </div>
          )}
        </div>
      </Header>
      <Content style={{ padding: '0 50px', marginTop: 64 }}>
        <div style={{ background: '#fff', padding: 24, minHeight: 'calc(100vh - 64px - 70px)' }}>
          <Outlet />
        </div>
      </Content>
      <Footer style={{ textAlign: 'center' }}>
        图书商城 ©{new Date().getFullYear()} 版权所有
      </Footer>
    </Layout>
  );
};

export default FrontLayout; 